/* 职责

  -- 路由容器 --
  -- 路由请求 -- 

*/

var express = require('express')
var fs = require('fs')
const path = require('path')
// 导入数据库
var pool = require('./sql')
var router = express.Router()
// 导入token
var jwt = require('./jwt')
// 导入文件上传中间件 
var multer = require('multer')
// 文件保存路径
var upload = multer({
  dest: path.join(__dirname, './public/upload/')
})

// 默认请求地址
var pathUrl = '/api/v1'

// 音乐列表接口
router.get(pathUrl + '/music', (req, res) => {
  var filepath = './db.json'
  fs.readFile(filepath, (err, data) => {
    if (err) return err
    var data = JSON.parse(data).music
    res.status(200).json({
      data,
      meta: {
        status: 200,
        message: '获取成功'
      }
    })
  })
})


// 获取文章列表
router.get(pathUrl + '/more', (req, res) => {
  var title = req.query.query //查询参数 可以为空
  var content = []
  if (title !== '' && title !== undefined) {
    content.push("%" + title + "%")
    pool.exec({
      // 模糊查询
      sql: 'select * from article where title like ?',
      params: content,
      success: suc => {
        if (!suc) return res.json({
          err: '获取失败',
          meta: {
            status: 500,
            message: '获取失败'
          }
        })
        res.json({
          data: {
            mores: suc
          },
          meta: {
            status: 200,
            message: '获取文章成功'
          }
        })
      }
    })
  } else {
    let page = req.query.pagenum == 0 ? 0 : req.query.pagenum - 1
    let pagesize = req.query.pagesize
    let starPage = page * pagesize
    let count = 'select count(*) as count from article' //所有总条数
    let sql = `select * from article limit ${starPage}, ${pagesize}` // 每一页的数据
    pool.exec({
      sql: count,
      success: data => {
        let count = data[0].count //总的条数
        pool.exec({
          sql: sql,
          success: suc => {
            if (!suc) return res.json({
              err: '获取失败',
              meta: {
                status: 500,
                message: '获取失败'
              }
            })
            res.json({
              data: {
                mores: suc,
                totalpage: count,
                pagenum: Number(page)
              },
              meta: {
                status: 200,
                message: '获取文章成功'
              }
            })
          }
        })
      }
    })
  }
})

//添加文章
router.post(pathUrl + '/more', (req, res) => {
  var body = req.body //获取传递过来的数据
  var title = body.title
  var des = body.des
  var content = body.content
  var img = body.img
  var date = Date.now()
  pool.exec({
    sql: 'insert into article values(?,?,?,?,?,?,?)',
    params: [null, title, des, content, date, date, img],
    success: data => {
      if (!data) return res.json({
        err: '错误',
        meta: {
          status: 500,
          message: '添加失败'
        }
      })
      res.json({
        data,
        meta: {
          status: 201,
          message: '添加文章成功'
        }
      })
    }
  })
})


// 修改文章内容
router.put(pathUrl + '/more', (req, res) => {
  const id = req.body.id
  const title = req.body.title
  const des = req.body.des
  const content = req.body.content
  const img = req.body.img
  const newdate = Date.now()
  pool.exec({
    sql: 'update article set  title=?, des=?, content=?, newtime=?, img=? where id = ?',
    params: [title, des, content, newdate, img, id],
    success: data => {
      if (!data) return res.json({
        error: '修改错误',
        meta: {
          status: 500,
          message: '修改失败'
        }
      })
      res.json({
        data,
        meta: {
          status: 200,
          message: '修改成功'
        }
      })
    }
  })
})


// 根据ID查询文章内容
router.get(pathUrl + '/mores', (req, res) => {
  const id = Number(req.query.id)
  pool.exec({
    sql: 'select * from article where id = ?',
    params: [id],
    success: data => {
      if (!data) return res.json({
        err,
        meta: {
          status: 500,
          message: '查询失败'
        }
      })
      if (data == '') return res.json({
        error: '查询错误',
        meta: {
          status: 500,
          message: '查询错误'
        }
      })
      res.json({
        data,
        meta: {
          status: 200,
          message: '查询成功'
        }
      })
    }
  })
})

// 删除单个文章
router.delete(pathUrl + '/more', (req, res) => {
  var id = req.query.id
  pool.exec({
    sql: 'delete from article where id = ?',
    params: [id],
    success: data => {
      if (!data) return res.json({
        err: '错误',
        meta: {
          status: 500,
          message: '删除失败'
        }
      })
      res.json({
        data,
        meta: {
          status: 201,
          message: '删除成功'
        }
      })
    }
  })
})

// 登录请求
router.post(pathUrl + '/login', (req, res) => {
  var name = req.body.name // 用户名
  var password = req.body.password // 密码
  var sql = 'select * from user where name = ? and password = ?'
  var content = [name, password]
  pool.exec({
    sql: sql,
    params: content,
    success: data => {
      if (data.length == 0) {
        res.json({
          err: '错误',
          meta: {
            status: 502,
            message: '认证失败'
          }
        })
      } else {
        // 创建token
        var tokens = jwt.createToken(name)
        data[0].token = tokens
        res.json({
          data: data,
          meta: {
            status: 200,
            message: '登录成功'
          }
        })
      }
    }
  })
})

// 上传图片请求
router.post(pathUrl + '/img', upload.single('file'), async (req, res) => {
  const file = req.file
  file.url = `http://localhost:3000/public/upload/${file.filename}`
  res.send(file)
})

module.exports = router